<template>
    <div class="sku-info">
        <div class="component-title">
            <h3>商品规格信息</h3>
        </div>

        <el-form label-width="120px" ref="skuForm">
            <!-- 规格设置部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-s-grid"></i>
                    <span>规格设置</span>
                </div>

                <p class="section-desc">选择规格属性组合生成SKU</p>

                <div class="spec-selector">
                    <div class="spec-group" v-for="(spec, specName) in specOptions" :key="specName">
                        <div class="spec-name">{{ specName }}</div>
                        <div class="spec-values">
                            <el-tag v-for="value in spec" :key="value"
                                :type="isSpecSelected(specName, value) ? 'primary' : 'info'" effect="plain"
                                @click="toggleSpecValue(specName, value)" closable :disable-transitions="false"
                                @close="removeSpecValue(specName, value)">
                                {{ value }}
                            </el-tag>
                            <el-input class="spec-input" v-if="inputVisible[specName]" v-model="inputValue[specName]"
                                ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(specName)"
                                @blur="handleInputConfirm(specName)">
                            </el-input>
                            <el-button v-else class="spec-button" size="small" @click="showInput(specName)">+
                                添加</el-button>
                        </div>
                    </div>

                    <div class="add-spec-group">
                        <el-button type="primary" size="small" @click="showSpecNameInput">
                            <i class="el-icon-plus"></i> 添加规格项
                        </el-button>
                    </div>

                    <el-dialog title="添加规格项" :visible.sync="specNameDialogVisible" width="30%"
                        :before-close="handleSpecNameDialogClose">
                        <el-form :model="newSpecGroup" label-width="80px">
                            <el-form-item label="规格名称">
                                <el-input v-model="newSpecGroup.name" placeholder="例如：颜色、尺寸等"></el-input>
                            </el-form-item>
                            <el-form-item label="规格值">
                                <el-tag v-for="(value, index) in newSpecGroup.values" :key="index" closable
                                    :disable-transitions="false" @close="newSpecGroup.values.splice(index, 1)">
                                    {{ value }}
                                </el-tag>
                                <el-input class="spec-input" v-if="newSpecValueInputVisible" v-model="newSpecValueInput"
                                    ref="newSpecValueInput" size="small"
                                    @keyup.enter.native="handleNewSpecValueInputConfirm"
                                    @blur="handleNewSpecValueInputConfirm">
                                </el-input>
                                <el-button v-else class="spec-button" size="small" @click="showNewSpecValueInput">+
                                    添加</el-button>
                            </el-form-item>
                        </el-form>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="specNameDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="addSpecGroup">确 定</el-button>
                        </span>
                    </el-dialog>
                </div>
            </div>

            <!-- SKU列表部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-tickets"></i>
                    <span>SKU列表</span>
                </div>

                <p class="section-desc">根据选择的规格组合自动生成SKU列表，您可以设置价格和库存等信息</p>

                <div class="batch-actions">
                    <el-button size="small" @click="batchDialogVisible = true">批量设置</el-button>
                    <el-button size="small" type="danger" @click="clearSkus">清空SKU</el-button>
                    <el-button size="small" type="primary" @click="generateSkus" :loading="isGenerating"
                        :disabled="isGenerating">
                        {{ isGenerating ? `生成中(${generationProgress}%)` : '生成SKU' }}
                    </el-button>
                    <el-button size="small" type="info" @click="togglePagination" v-if="skuList.length > pageSize">
                        {{ paginationEnabled ? '取消分页' : '启用分页' }}
                    </el-button>
                </div>

                <el-table :data="displaySkuList" border style="width: 100%" v-if="skuList.length > 0"
                    v-loading="tableLoading" element-loading-text="处理中..." height="450">
                    <el-table-column label="规格组合" min-width="180">
                        <template slot-scope="scope">
                            <div class="sku-spec-tags">
                                <el-tag v-for="(value, name) in scope.row.spec_data" :key="name" size="small"
                                    effect="plain">
                                    {{ name }}: {{ value }}
                                </el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="SKU编码" width="180">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.sku_code" placeholder="请输入SKU编码"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="销售价格" width="150">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.price" :precision="2" :step="0.01" :min="0"
                                controls-position="right" size="small"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="市场价" width="150">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.market_price" :precision="2" :step="0.01" :min="0"
                                controls-position="right" size="small"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="成本价" width="150">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.cost_price" :precision="2" :step="0.01" :min="0"
                                controls-position="right" size="small"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存" width="120">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.stock" :min="0" controls-position="right"
                                size="small"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存预警" width="120">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.stock_warning" :min="0" controls-position="right"
                                size="small"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" fixed="right">
                        <template slot-scope="scope">
                            <el-button type="text" size="small"
                                @click="removeSku(scope.$index + ((currentPage - 1) * pageSize))"
                                style="color: #F56C6C;">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页控件 -->
                <div class="pagination-container" v-if="paginationEnabled && skuList.length > 0">
                    <el-pagination @size-change="handlePageSizeChange" @current-change="handlePageChange"
                        :current-page="currentPage" :page-sizes="pageSizes" :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper" :total="skuList.length">
                    </el-pagination>
                </div>

                <div class="empty-sku" v-if="skuList.length === 0">
                    <i class="el-icon-goods"></i>
                    <p>暂无SKU数据，请选择规格属性后点击"生成SKU"按钮</p>
                </div>

                <!-- 批量设置对话框 -->
                <el-dialog title="批量设置" :visible.sync="batchDialogVisible" width="40%">
                    <el-form :model="batchForm" label-width="120px">
                        <el-form-item label="销售价格">
                            <el-input-number v-model="batchForm.price" :precision="2" :step="0.01" :min="0"
                                controls-position="right"></el-input-number>
                        </el-form-item>
                        <el-form-item label="市场价">
                            <el-input-number v-model="batchForm.market_price" :precision="2" :step="0.01" :min="0"
                                controls-position="right"></el-input-number>
                        </el-form-item>
                        <el-form-item label="成本价">
                            <el-input-number v-model="batchForm.cost_price" :precision="2" :step="0.01" :min="0"
                                controls-position="right"></el-input-number>
                        </el-form-item>
                        <el-form-item label="库存">
                            <el-input-number v-model="batchForm.stock" :min="0"
                                controls-position="right"></el-input-number>
                        </el-form-item>
                        <el-form-item label="库存预警">
                            <el-input-number v-model="batchForm.stock_warning" :min="0"
                                controls-position="right"></el-input-number>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="batchDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="applyBatchSettings">应 用</el-button>
                    </div>
                </el-dialog>
            </div>
        </el-form>
    </div>
</template>

<script>
export default {
    name: 'SkuInfo',
    props: {
        skuList: {
            type: Array,
            required: true
        }
    },
    data() {
        return {
            // 规格选择相关
            specOptions: {
                '颜色': ['黑色', '白色', '蓝色'],
                '内存': ['64GB', '128GB', '256GB']
            },
            selectedSpecs: {
                '颜色': [],
                '内存': []
            },
            inputVisible: {},
            inputValue: {},

            // 新增规格相关
            specNameDialogVisible: false,
            newSpecGroup: {
                name: '',
                values: []
            },
            newSpecValueInputVisible: false,
            newSpecValueInput: '',

            // 批量设置相关
            batchDialogVisible: false,
            batchForm: {
                price: 0,
                market_price: 0,
                cost_price: 0,
                stock: 0,
                stock_warning: 10
            },

            // 性能优化相关
            isGenerating: false,
            generationProgress: 0,
            maxSkuCount: 100,
            tableLoading: false,
            paginationEnabled: false,
            currentPage: 1,
            pageSize: 10,
            pageSizes: [10, 20, 50, 100]
        };
    },
    computed: {
        // 分页后的SKU列表
        displaySkuList() {
            if (!this.paginationEnabled || this.skuList.length <= this.pageSize) {
                return this.skuList;
            }

            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.skuList.slice(start, end);
        },
        // 总页数
        totalPages() {
            return Math.ceil(this.skuList.length / this.pageSize);
        }
    },
    watch: {
        skuList: {
            handler(newVal) {
                // 当SKU数量超过阈值时，自动启用分页
                if (newVal.length > this.pageSize && !this.paginationEnabled) {
                    this.paginationEnabled = true;
                    this.$message.info(`SKU数量较多，已自动启用分页显示`);
                }
            },
            immediate: true
        }
    },
    methods: {
        // 规格值选择相关方法
        isSpecSelected(specName, value) {
            return this.selectedSpecs[specName] && this.selectedSpecs[specName].includes(value);
        },
        toggleSpecValue(specName, value) {
            if (!this.selectedSpecs[specName]) {
                this.$set(this.selectedSpecs, specName, []);
            }

            const index = this.selectedSpecs[specName].indexOf(value);
            if (index === -1) {
                this.selectedSpecs[specName].push(value);
            } else {
                this.selectedSpecs[specName].splice(index, 1);
            }
        },
        removeSpecValue(specName, value) {
            const index = this.specOptions[specName].indexOf(value);
            if (index !== -1) {
                this.specOptions[specName].splice(index, 1);
            }

            // 同时从已选中的规格中移除
            if (this.selectedSpecs[specName]) {
                const selectedIndex = this.selectedSpecs[specName].indexOf(value);
                if (selectedIndex !== -1) {
                    this.selectedSpecs[specName].splice(selectedIndex, 1);
                }
            }
        },
        showInput(specName) {
            this.$set(this.inputVisible, specName, true);
            this.$set(this.inputValue, specName, '');
            this.$nextTick(_ => {
                this.$refs.saveTagInput[0].$refs.input.focus();
            });
        },
        handleInputConfirm(specName) {
            const inputValue = this.inputValue[specName];
            if (inputValue && this.specOptions[specName].indexOf(inputValue) === -1) {
                this.specOptions[specName].push(inputValue);
            }
            this.inputVisible[specName] = false;
            this.inputValue[specName] = '';
        },

        // 添加规格组相关方法
        showSpecNameInput() {
            this.specNameDialogVisible = true;
            this.newSpecGroup = {
                name: '',
                values: []
            };
        },
        handleSpecNameDialogClose() {
            this.specNameDialogVisible = false;
        },
        showNewSpecValueInput() {
            this.newSpecValueInputVisible = true;
            this.newSpecValueInput = '';
            this.$nextTick(_ => {
                this.$refs.newSpecValueInput.$refs.input.focus();
            });
        },
        handleNewSpecValueInputConfirm() {
            const value = this.newSpecValueInput;
            if (value && this.newSpecGroup.values.indexOf(value) === -1) {
                this.newSpecGroup.values.push(value);
            }
            this.newSpecValueInputVisible = false;
            this.newSpecValueInput = '';
        },
        addSpecGroup() {
            if (this.newSpecGroup.name && this.newSpecGroup.values.length > 0) {
                this.$set(this.specOptions, this.newSpecGroup.name, [...this.newSpecGroup.values]);
                this.$set(this.selectedSpecs, this.newSpecGroup.name, []);
                this.specNameDialogVisible = false;
            } else {
                this.$message.warning('规格名称和规格值不能为空');
            }
        },

        // SKU相关方法
        generateSkus() {
            if (this.isGenerating) return;

            const specNames = Object.keys(this.selectedSpecs);
            const hasSelectedSpecs = specNames.some(name => this.selectedSpecs[name].length > 0);

            if (!hasSelectedSpecs) {
                this.$message.warning('请至少选择一个规格值');
                return;
            }

            // 计算可能的组合数量
            let totalCombinations = 1;
            specNames.forEach(name => {
                if (this.selectedSpecs[name].length > 0) {
                    totalCombinations *= this.selectedSpecs[name].length;
                }
            });

            if (totalCombinations > this.maxSkuCount) {
                this.$confirm(`生成的SKU数量(${totalCombinations})超过了最大限制(${this.maxSkuCount})，可能导致页面卡顿，是否继续?`, '警告', {
                    confirmButtonText: '继续',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.doGenerateSkus(specNames, totalCombinations);
                }).catch(() => {
                    // 用户取消操作
                });
            } else {
                this.doGenerateSkus(specNames, totalCombinations);
            }
        },

        doGenerateSkus(specNames, totalCombinations) {
            this.isGenerating = true;
            this.tableLoading = true;
            this.generationProgress = 0;

            // 创建新的SKU列表
            const newSkuList = [];

            // 获取当前已存在的SKU，用于保留已设置的价格和库存
            const existingSkuMap = new Map();
            this.skuList.forEach(sku => {
                const key = this.getSkuSpecKey(sku.spec_data);
                existingSkuMap.set(key, sku);
            });

            // 生成所有可能的规格组合
            const generateCombinations = (index, current) => {
                if (index === specNames.length) {
                    // 检查是否已存在相同规格的SKU
                    const key = this.getSkuSpecKey(current);
                    const existingSku = existingSkuMap.get(key);

                    if (existingSku) {
                        // 使用已存在的SKU数据
                        newSkuList.push({ ...existingSku });
                    } else {
                        // 创建新的SKU
                        newSkuList.push({
                            sku_code: this.generateSkuCode(current),
                            name: this.generateSkuName(current),
                            price: this.batchForm.price,
                            market_price: this.batchForm.market_price,
                            cost_price: this.batchForm.cost_price,
                            stock: this.batchForm.stock,
                            stock_warning: this.batchForm.stock_warning,
                            weight: 0,
                            volume: 0,
                            spec_data: { ...current },
                            limit_per_order: null
                        });
                    }

                    // 更新进度
                    this.generationProgress = Math.floor((newSkuList.length / totalCombinations) * 100);
                    return;
                }

                const specName = specNames[index];
                const specValues = this.selectedSpecs[specName];

                if (specValues.length === 0) {
                    // 如果该规格没有选择值，跳过
                    generateCombinations(index + 1, current);
                } else {
                    // 为每个规格值生成组合
                    for (let i = 0; i < specValues.length; i++) {
                        const newCurrent = { ...current };
                        newCurrent[specName] = specValues[i];
                        generateCombinations(index + 1, newCurrent);
                    }
                }
            };

            // 使用Web Worker或分批处理来避免UI阻塞
            setTimeout(() => {
                try {
                    // 开始生成组合
                    generateCombinations(0, {});

                    // 更新SKU列表
                    this.$emit('update-sku-list', newSkuList);

                    // 如果生成的SKU数量较多，自动启用分页
                    if (newSkuList.length > this.pageSize && !this.paginationEnabled) {
                        this.paginationEnabled = true;
                        this.currentPage = 1;
                    }

                    this.$message.success(`成功生成${newSkuList.length}个SKU`);
                } catch (error) {
                    this.$message.error('生成SKU时出错: ' + error.message);
                } finally {
                    this.isGenerating = false;
                    this.tableLoading = false;
                    this.generationProgress = 100;
                }
            }, 50);
        },

        getSkuSpecKey(specData) {
            // 生成规格组合的唯一键
            const keys = Object.keys(specData).sort();
            return keys.map(key => `${key}:${specData[key]}`).join('|');
        },
        generateSkuCode(specData) {
            // 生成SKU编码
            const timestamp = Date.now().toString().slice(-6);
            const specValues = Object.values(specData).join('');
            const hash = this.simpleHash(specValues);
            return `SKU${timestamp}${hash}`;
        },
        simpleHash(str) {
            // 简单的哈希函数，用于生成短哈希
            let hash = 0;
            for (let i = 0; i < str.length; i++) {
                const char = str.charCodeAt(i);
                hash = ((hash << 5) - hash) + char;
                hash = hash & hash; // 转换为32位整数
            }
            return Math.abs(hash % 1000).toString().padStart(3, '0');
        },
        generateSkuName(specData) {
            // 生成SKU名称
            return Object.entries(specData)
                .map(([name, value]) => `${value}`)
                .join(' ');
        },
        removeSku(index) {
            const newSkuList = [...this.skuList];
            newSkuList.splice(index, 1);
            this.$emit('update-sku-list', newSkuList);
        },
        clearSkus() {
            this.$confirm('确定要清空所有SKU吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$emit('update-sku-list', []);
            }).catch(() => { });
        },

        // 批量设置相关方法
        applyBatchSettings() {
            try {
                this.tableLoading = true;

                const newSkuList = this.skuList.map(sku => {
                    const newSku = { ...sku };
                    for (const key in this.batchForm) {
                        if (this.batchForm[key] !== null && this.batchForm[key] !== undefined) {
                            newSku[key] = this.batchForm[key];
                        }
                    }
                    return newSku;
                });

                this.$emit('update-sku-list', newSkuList);
                this.batchDialogVisible = false;
                this.$message.success('批量设置成功');
            } catch (error) {
                console.error('批量设置失败:', error);
                this.$message.error('批量设置失败: ' + (error.message || '未知错误'));
            } finally {
                this.tableLoading = false;
            }
        },

        // 分页相关方法
        handlePageChange(page) {
            this.currentPage = page;
        },

        handlePageSizeChange(size) {
            this.pageSize = size;
            this.currentPage = 1;
        },

        togglePagination() {
            this.paginationEnabled = !this.paginationEnabled;
            if (this.paginationEnabled) {
                this.currentPage = 1;
            }
        },

        validate() {
            return new Promise((resolve, reject) => {
                if (this.skuList.length === 0) {
                    reject(new Error('请至少添加一个SKU'));
                    return;
                }

                for (let i = 0; i < this.skuList.length; i++) {
                    const sku = this.skuList[i];
                    if (!sku.sku_code) {
                        reject(new Error(`第${i + 1}个SKU的编码不能为空`));
                        return;
                    }
                    if (sku.price <= 0) {
                        reject(new Error(`第${i + 1}个SKU的销售价格必须大于0`));
                        return;
                    }
                }

                resolve(true);
            });
        }
    }
};
</script>

<style scoped>
.sku-info {
    padding: 20px;
}

.component-title {
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.component-title h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.form-section {
    margin-bottom: 30px;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 4px;
}

.section-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.section-title i {
    margin-right: 8px;
    color: #409EFF;
}

.section-desc {
    color: #999;
    font-size: 12px;
    margin-bottom: 20px;
}

.spec-selector {
    margin-bottom: 20px;
}

.spec-group {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px dashed #eee;
}

.spec-name {
    font-weight: 600;
    margin-bottom: 10px;
    color: #555;
}

.spec-values {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.spec-input {
    width: 100px;
    margin-right: 8px;
    vertical-align: bottom;
}

.spec-button {
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.add-spec-group {
    margin-top: 20px;
}

.batch-actions {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.sku-spec-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.empty-sku {
    text-align: center;
    padding: 40px 0;
    color: #999;
}

.empty-sku i {
    font-size: 48px;
    color: #ddd;
    margin-bottom: 15px;
}

.pagination-container {
    margin-top: 15px;
    display: flex;
    justify-content: center;
}
</style>